'use strict';

const Controller = require('egg').Controller;
class UserController extends Controller {
  // 登录
  async login() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const res = await ctx.service.user.login();
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    } else {
      resMsg.data = res.data;
    }
    ctx.body = resMsg;
  }
  // 获取登录用户信息
  async getUserInfo() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const token = ctx.request.headers.token;
    const res = await ctx.service.user.getUserInfo(token);

    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    } else {
      resMsg.data = res.data;
    }

    ctx.body = resMsg;
  }

  // 修改密码
  async updatePassword() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const payload = ctx.request.body;
    const token = ctx.request.headers.token;
    const checkAuth = await ctx.service.authorize.checkAuth(token);
    if (checkAuth.errcode) {
      ctx.body = resMsg;
      return false;
    }
    payload.userId = checkAuth.data.userId;
    payload.identity = checkAuth.data.identity;
    const res = await ctx.service.user.updatePassword(payload);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    } else {
      resMsg.data = res.data;
    }

    ctx.body = resMsg;
  }
}

module.exports = UserController;
